package com.ang.filter.filters.filterRegistrationBean;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author ssang
 * @date 2023-11-02 10:21
 */
public class MyFilterRegistrationBean2 implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入过滤器：MyFilterRegistrationBean2");
        Object attribute = servletRequest.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        System.out.println(attribute);
        Object uri = servletRequest.getAttribute(RequestDispatcher.ERROR_REQUEST_URI);
        System.out.println(uri);
        if(Objects.equals(attribute, HttpStatus.NOT_FOUND.value())){
            servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE);
            servletResponse.setCharacterEncoding(StandardCharsets.UTF_8.name());
            servletResponse.getWriter().write("请求地址："+uri+"，不存在");
        }else if(Objects.equals(attribute, HttpStatus.INTERNAL_SERVER_ERROR.value())){
            servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE);
            servletResponse.setCharacterEncoding(StandardCharsets.UTF_8.name());
            servletResponse.getWriter().write("请求地址："+uri+"，发生内部错误");
        }else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
        System.out.println("出过滤器：MyFilterRegistrationBean2");
    }
}
